<template>
    <div>
        <el-divider content-position="left">您具有一定的操作权限</el-divider>
    </div>

    <div>
        <el-divider>
            <span id="spanlittlepart">查询</span>
        </el-divider>
    </div>

    <!-- 查询 -->
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="商品名" style="width: 150px;">
            <el-input v-model="checkformInline.com_name" placeholder="com_name"></el-input>
        </el-form-item>
        <el-form-item label="产地" style="width: 100px;">
            <el-input v-model="checkformInline.com_place" placeholder="com_place"></el-input>
        </el-form-item>
        <el-form-item label="发货地" style="width: 150px;">
            <el-input v-model="checkformInline.com_from" placeholder="com_from"></el-input>
        </el-form-item>
        <el-form-item label="预计x小时发货" style="width: 150px;">
            <el-input v-model="checkformInline.com_time" placeholder="com_time"></el-input>
        </el-form-item>
        <el-form-item style="width: 200px;">
            <el-button @click="search" type="primary" plain style="width: 200px;">查询</el-button>
        </el-form-item>
    </el-form>

    <el-divider>
        <el-icon><star-filled /></el-icon>
    </el-divider>

    <!-- 添加项 -->
    <el-button type="primary" plain class="addbtn" style="width: 100%;margin: 0 auto;" @click="onAddItem">
        <el-icon>
            <Edit />
        </el-icon>
        <span> 创建新的商品条目</span>
    </el-button>

    <!-- 展示表格 -->
    <el-table :border="parentBorder" :data="tableData" style="width: 100%" highlight-current-row="true"
        :scrollbar-always-on="true">
        <el-table-column prop="com_name" label="商品名" width="300" />
        <el-table-column prop="com_place" label="产地" width="" />
        <el-table-column prop="com_price" label="价格" width="" />
        <el-table-column prop="com_from" label="发货地" width="" />
        <el-table-column prop="express_fee" label="运费" width="" />
        <el-table-column prop="com_time" label="预计x小时发货" width="" />
        <el-table-column label="首页图片" width="150">
            <template #default="scope">
                <div style="display: flex; align-items: center">
                    <el-image
                        style="width: 100px; height: 100px; padding-left: -30px;margin-left: -30px; overflow: visible;"
                        :src="baseURL + tableData[(this.page - 1) * this.size + scope.$index].first_img"
                        :preview-src-list="[baseURL + tableData[(this.page - 1) * this.size + scope.$index].first_img]"
                        :preview-teleported="true" :initial-index="scope.$index" />
                </div>
            </template>
        </el-table-column>

        <el-table-column label="商品图片" width="200" v-if="tableimg != null">
            <template #default="scope">
                <el-button @click="showDesc(scope.$index, scope.row)" style="margin-left: -10px;">点击查看商品详情图片</el-button>
            </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
            <template #default="scope">
                <el-button link type="primary" size="small"
                    @click.prevent="handleEdit(scope.$index, scope.row)">编辑</el-button>
                <el-button link type="primary" size="small"
                    @click.prevent="handleDelete(scope.$index, scope.row)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>

    <!-- Form -->
    <el-dialog v-model="dialogFormVisible" title="编辑">
        <el-form :model="form">
            <el-form-item label="商品名" :label-width="formLabelWidth">
                <el-input v-model="form.com_name" autocomplete="off" />
            </el-form-item>
            <el-form-item label="产地" :label-width="formLabelWidth">
                <el-input v-model="form.com_place" autocomplete="off" />
            </el-form-item>
            <el-form-item label="价格" :label-width="formLabelWidth">
                <el-input v-model="form.com_price" autocomplete="off" />
            </el-form-item>
            <el-form-item label="发货地" :label-width="formLabelWidth">
                <el-input v-model="form.com_from" autocomplete="off" />
            </el-form-item>
            <el-form-item label="运费" :label-width="formLabelWidth">
                <el-input v-model="form.express_fee" autocomplete="off" />
            </el-form-item>
            <el-form-item label="预计x小时发货" :label-width="formLabelWidth">
                <el-input v-model="form.com_time" autocomplete="off" />
            </el-form-item>
        </el-form>
        <el-upload v-model:file-list="editfileList" class="upload-demo" action="#" :on-preview="handlePreview"
            :auto-upload="false" :before-upload="handleChange" :on-remove="handleRemove" list-type="picture"
            :multiple="true" :limit="8">
            <el-button type="primary">点击进行商品详情图片上传</el-button>
            <template #tip>
                <div class="el-upload__tip">
                    只能上传图片文件，如上传多张图片：图片总大小应小于1MB，如超过1MB请压缩图片或进行多次上传
                </div>
            </template>
        </el-upload>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="onSaveInfo">
                    提交
                </el-button>
            </span>
        </template>
    </el-dialog>

    <el-pagination background layout="prev, pager, next" :current-page="page" @update:current-page="handleCurrentChange"
        :total="total" :page-size="size" style="bottom: 0; text-align: center;margin-left: 45%;margin-top: 5px;" />

    <!-- Form -->
    <el-dialog v-model="dialogaddFormVisible" title="添加商品项">
        <el-form :model="addform" ref="formRef">
            <el-form-item label="商品名" :label-width="formLabelWidth" :rules="[
                    { required: true, message: 'age is required' },
                ]">
                <el-input v-model="addform.com_name" autocomplete="off" />
            </el-form-item>
            <el-form-item label="产地" :label-width="formLabelWidth" :rules="[
                    { required: true, message: 'age is required' },
                ]">
                <el-input v-model="addform.com_place" autocomplete="off" />
            </el-form-item>
            <el-form-item label="价格" :label-width="formLabelWidth" :rules="[
                    { required: true, message: 'age is required' },
                    { type: 'number', message: 'age must be a number' },
                ]">
                <el-input v-model.number="addform.com_price" autocomplete="off" />
            </el-form-item>
            <el-form-item label="发货地" :label-width="formLabelWidth" :rules="[
                    { required: true, message: 'age is required' },
                ]">
                <el-input v-model="addform.com_from" autocomplete="off" />
            </el-form-item>
            <el-form-item label="运费" :label-width="formLabelWidth" :rules="[
                    { required: true, message: 'age is required' },
                    { type: 'number', message: 'age must be a number' },
                ]">
                <el-input v-model.number="addform.express_fee" autocomplete="off" />
            </el-form-item>
            <el-form-item label="预计x小时发货" :label-width="formLabelWidth" :rules="[
                    { required: true, message: 'age is required' },
                    { type: 'number', message: 'age must be a number' },
                ]">
                <el-input v-model.number="addform.com_time" autocomplete="off" />
            </el-form-item>
            <el-upload v-model:file-list="fileList" class="upload-demo" action="#" :on-preview="handlePreview"
                :auto-upload="false" :before-upload="handleChange" :on-remove="handleRemove" list-type="picture"
                :multiple="true" :limit="5">
                <el-button type="primary">点击进行商品详情图片上传</el-button>
                <template #tip>
                    <div class="el-upload__tip">
                        只能上传图片文件，如上传多张图片：图片总大小应小于1MB，如超过1MB请压缩图片或进行多次上传
                    </div>
                </template>
            </el-upload>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="closemodal">取消</el-button>
                <el-button type="primary" @click="onAddInfo">
                    确定
                </el-button>
            </span>
        </template>
    </el-dialog>
    <!-- 查看商品详情 -->
    <el-dialog v-model="dialogdescFormVisible" title="商品详情图片">
        <el-form :model="tableData[desci].comimgs">
            <div v-for="(item, i) in tableData[(this.page - 1) * this.size + desci].comimgs" :key="i">
                <el-image
                    style=" padding-left: -30px;margin-left: -30px;margin-right: 40px;margin-bottom: 10px; overflow: visible; display: block; "
                    :src="item" :preview-src-list="tableData[(this.page - 1) * this.size + desci].comimgs"
                    :preview-teleported="true" :initial-index="i" />
            </div>
        </el-form>
    </el-dialog>
</template>
<script setup>
import {
    Guide,
    PictureFilled,
    User,
    HomeFilled,
    ChatLineSquare,
    Apple,
    Document,
    List,
    Tools,
    ShoppingCart,
    CollectionTag,
    Finished,
    InfoFilled,
    Cherry,
    Goods,
    Sell,
    ShoppingCartFull,
    Van,
    Sunrise,
    StarFilled,
    EditPen,
    Edit,
    Promotion,
    Grape,
    Pear,
} from '@element-plus/icons-vue';
import dayjs from 'dayjs';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';
import { reactive, ref } from 'vue'

const formRef = ref()


const submitForm = (formEl) => {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            console.log('submit!')
        } else {
            console.log('error submit!')
            return false
        }
    })
}

const parentBorder = ref(false)
const formLabelWidth = '140px';

</script>
<script>

export default {
    setup() {

    },
    data() {
        return {
            baseURL: "http://localhost:8080",
            fileList: [],
            formInline: {
                commodityid: 0,
                com_name: '',
                com_place: '',
                com_price: 0.0,
                com_from: '',
                express_fee: 9999,
                com_time: 0,
                first_img: ''
            },
            checkformInline: {
                commodityid: 0,
                com_name: '',
                com_place: '',
                com_price: 0.0,
                com_from: '',
                express_fee: 9999,
                com_time: '',
                first_img: ''
            },
            dialogFormVisible: false,
            dialogaddFormVisible: false,
            dialogdescFormVisible: false,
            showSearch: false,
            tableData: [],
            tableDataStore: [],
            tableimgList: [],
            tableimgListList: [],
            tableimgListmore: [],
            formdesc: [],
            editfileList: [],   //编辑modal种商品描述图片的列表
            desci: 0,
            tableimg: '',
            othertableimgList: [],
            othertableimg: '',
            buy: {
                commodityid: 0,
                com_name: '',
                com_place: '',
                com_price: 0.0,
                com_from: '',
                express_fee: 9999,
                com_time: 0,
                first_img: ''
            },
            form: {
                commodityid: 0,
                com_name: '',
                com_place: '',
                com_price: '',
                com_from: '',
                express_fee: 9999,
                com_time: 0,
                first_img: ''
            },
            addform: {
                commodityid: 0,
                com_name: '',
                com_place: '',
                com_price: '',
                com_from: '',
                express_fee: '',
                com_time: '',
                first_img: ''
            },
            searchForm: [],
            filetype: [
                "jpg",
                "jpeg",
                "png",
            ],
            page: 1, // 当前页码
            total: 0, // 总条数
            size: 10, // 每页的数据条数
            reallyTable: [],
            selData: [],
            fileArray: []
        }
    },
    methods: {
        init() {
            axios({
                method: 'post',
                url: 'http://localhost:8080/buy/getbuybuydescbackend',
                withCredentials: true,
            }).then(res => {
                this.tableData = res.data.data;
                this.selData = res.data.data
                this.tableDataStore = res.data.data;
                this.tableData = res.data.data.slice(
                    (this.page - 1) * this.size,
                    this.page * this.size
                );
                console.log(this.tableData);
                this.total = res.data.data.length;

                this.selData = res.data.data;
                this.othertableimgList = []
                for (var i = 0; i < res.data.data.length; i++) {
                    console.log('for')
                    if (res.data.data[i].comimgs != null) {
                        if (Array.isArray(res.data.data[i].comimgs)) {
                            for (let j = 0; j < res.data.data[i].comimgs.length; j++) {
                                res.data.data[i].comimgs[j] = this.baseURL + res.data.data[i].comimgs[j]
                            }
                            this.tableimgListList[i] = res.data.data[i].comimgs
                            this.tableimg = this.baseURL + this.tableimgListList[0][0];
                            console.log(this.tableimgListList);
                            this.othertableimgList.push(this.baseURL + res.data.data[i].first_img);
                            console.log(this.othertableimgList);
                            this.othertableimg = this.baseURL + this.othertableimgList[0];

                            this.formdesc[i] = res.data.data[i].comimgs
                        } else {
                            this.tableimgList.push(res.data.data[i].comimgs);
                            console.log(this.tableimgList);
                            this.tableimg = this.baseURL + this.tableimgList[0];
                            this.othertableimgList.push(this.baseURL + res.data.data[i].first_img);
                            this.othertableimg = this.baseURL + this.othertableimgList[0];

                            this.formdesc[i].push(res.data.data[i].comimgs)
                        }
                    } else {
                        console.log('else')
                    }
                }

            })
        },
        search() {
            let arr = []
            console.log(this.tableDataStore.length)
            for (let i = 0; i < this.tableDataStore.length; i++) {
                if (String(this.tableDataStore[i].com_name).includes(this.checkformInline.com_name) &&
                    String(this.tableDataStore[i].com_place).includes(this.checkformInline.com_place) &&
                    String(this.tableDataStore[i].com_from).includes(this.checkformInline.com_from) &&
                    String(this.tableDataStore[i].com_time).includes(this.checkformInline.com_time)) {
                    arr.push(this.tableDataStore[i])
                }
            }
            console.log(arr);
            this.total = arr.length
            this.page = 1
            this.tableData = arr.slice(
                (this.page - 1) * this.size,
                this.page * this.size
            );
            this.selData = arr;
        },
        //删除表格行
        handleDelete(index, row) {
            console.log(index, row);
            console.log(row.commodityid);//可以获取到
            ElMessageBox.confirm(
                '确认删除本项吗？删除后无法找回:-0',
                'Warning',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            )
                .then(() => {
                    axios({
                        method: 'post',
                        url: 'http://localhost:8080/buy/delbuybackend',
                        withCredentials: true,
                        data: {
                            commodityid: row.commodityid,
                            first_img: row.first_img,
                            comimgs: row.comimgs
                        },
                    }).then(res => {
                        if (res.data.code == 200) {
                            ElMessage({
                                type: 'success',
                                message: '删除成功',
                            })
                            this.init()
                        }

                    })
                })
                .catch(() => {
                    ElMessage({
                        type: 'info',
                        message: '取消删除操作',
                    })
                })
        },
        filterArr(arr1, arr2) {
            var uid1 = []
            var uid2 = []
            for (var i in arr1) {
                uid1.push(arr1[i])
            }
            for (var j in arr2) {
                uid2.push(arr2[j])
            }
            const arr = [...uid1, ...uid2];
            console.log(arr);
            const newArr = arr.filter(item => {
                return !(uid2.includes(item));
            });
            return newArr;
        },
        //编辑表格行
        handleEdit(index, row) {
            let dif = this.filterArr([1, 2, 3], [2, 3, 4])
            console.log(dif);
            for (let i = 0; i < row.comimgs.length; i++) {
                this.editfileList[i] = { name: i, url: row.comimgs[i] }
            }
            // this.editfileList = row.comimgs
            this.dialogFormVisible = true;
            axios({
                method: 'post',
                url: 'http://localhost:8080/buy/getsingle',
                withCredentials: true,
                data: {
                    commodityid: index
                },
            }).then(res => {
                this.form = row;
            })
        },
        async onSaveInfo() {
            if (isNaN(this.form.com_price) || isNaN(this.form.express_fee || isNaN(this.form.com_time))) {
                alert("价格、运费、预计发货时间需为数字，请重新输入")
            } else if (this.form.com_from != '' && this.form.com_name != '' && this.form.com_place != '' && this.form.com_price != '' && this.form.com_time != '' && this.form.express_fee != '' && this.editfileList.length != 0) {
                const fileArray = this.editfileList;
                console.log(this.editfileList);
                this.fileArray = fileArray
                console.log(fileArray);
                for (let i = fileArray.length - 1; i >= 0; i--) {
                    if (fileArray[i].status == 'ready') {
                        console.log(i);
                        let lastName = this.getLastName(fileArray, i)
                        await this.getBase64(fileArray[i].url).then(res => {
                            this.fileArray[i].url = res
                            this.fileArray[i].name = new Date().getTime() + Math.floor(Math.random() * (0 - 1000)) + 1000 + '.' + lastName
                        })
                    }
                }

                axios({
                    method: 'post',
                    url: 'http://localhost:8080/buy/modifybuy',
                    withCredentials: true,
                    data: {
                        commodityid: this.form.commodityid,
                        com_name: this.form.com_name,
                        com_place: this.form.com_place,
                        com_price: parseFloat(this.form.com_price),
                        com_from: this.form.com_from,
                        express_fee: parseFloat(this.form.express_fee),
                        com_time: parseFloat(this.form.com_time),
                        descimg: this.fileArray,
                    },
                }).then(res => {
                    //console.log(11111111);
                    this.tableData = res.data.data;
                    this.tableDataStore = res.data.data;
                    this.init()
                    console.log(Array.isArray(res.data.data[0].allcomimgs))  //true

                })
                this.dialogFormVisible = false;
            } else {
                alert("存在未输入项，请检查")
            }
        },
        //增添项
        onAddItem() {
            this.dialogaddFormVisible = true;
        },
        getLastName(fileArray, i) {
            let pos = fileArray[i].name.lastIndexOf(".");
            let lastName = fileArray[i].name.substring(pos + 1, fileArray[i].name.length);
            return lastName
        },
        getBase64(imgUrl) {
            return new Promise((resolve, reject) => {
                if (!imgUrl) {
                    reject('请传入imgUrl内容')
                }
                window.URL = window.URL || window.webkitURL
                var xhr = new XMLHttpRequest()
                xhr.open('get', imgUrl, true)
                xhr.responseType = 'blob'
                xhr.onload = function () {
                    if (this.status == 200) {
                        // 得到一个blob对象
                        var blob = this.response
                        const oFileReader = new FileReader()
                        oFileReader.onloadend = function (e) {
                            const base64 = e.target.result
                            resolve(base64 || '')
                        }
                        oFileReader.readAsDataURL(blob)
                    }
                }
                xhr.send()

            })
        },
        async onAddInfo() {
            // formEl.validate(async (valid) => {
            if (isNaN(this.addform.com_price) || isNaN(this.addform.express_fee || isNaN(this.addform.com_time))) {
                alert("价格、运费、预计发货时间需为数字，请重新输入")
            } else if (this.addform.com_from != '' && this.addform.com_name != '' && this.addform.com_place != '' && this.addform.com_price != '' && this.addform.com_time != '' && this.addform.express_fee != '' && this.fileList.length != 0) {
                console.log('submit!')
                //上传图片到数据库
                const fileArray = this.fileList;
                console.log(this.fileList);
                this.fileArray = fileArray
                for (let i = fileArray.length - 1; i >= 0; i--) {
                    let lastName = this.getLastName(fileArray, i)
                    await this.getBase64(fileArray[i].url).then(res => {
                        this.fileArray[i].url = res
                        this.fileArray[i].name = new Date().getTime() + Math.floor(Math.random() * (0 - 1000)) + 1000 + '.' + lastName
                    })
                }

                console.log(this.fileArray);

                axios({
                    method: 'post',
                    url: 'http://localhost:8080/buy/additem',
                    withCredentials: true,
                    data: {
                        com_name: this.addform.com_name,
                        com_place: this.addform.com_place,
                        com_price: parseFloat(this.addform.com_price),
                        com_from: this.addform.com_from,
                        express_fee: parseFloat(this.addform.express_fee),
                        com_time: parseFloat(this.addform.com_time),
                        descimg: this.fileArray,
                    },
                }).then(res => {
                    this.tableData = res.data.data;
                    this.tableDataStore = res.data.data;
                    this.init()
                    console.log(Array.isArray(res.data.data[0].allcomimgs))  //true

                })

                this.dialogaddFormVisible = false;

            } else {
                alert("存在未输入项，请检查")
            }
            // })

        },
        async handleCurrentChange(val) {
            console.log(`当前页: ${val}`);
            this.page = val
            this.tableData = this.selData.slice(
                (this.page - 1) * this.size,
                this.page * this.size
            );
            console.log(this.tableData);
            // this.currentPage = val;
            const data = { 'page': val }
            // await this.onload(data)
        },
        handleRemove(file, fileList) {
            this.fileList = fileList
        },
        handlePreview(file) {
            console.log(file);
        },
        handleChange(file, fileList) {
            let isRightSize = file.size / 1024 / 1024 < 20
            if (!isRightSize) {
                this.$message.error('文件大小超过 20MB')
            }
            let fileName = file.name;
            let pos = fileName.lastIndexOf(".");
            let lastName = fileName.substring(pos, fileName.length);
            let isAccept = true;
            if (lastName.toLowerCase() !== ".jpg" && lastName.toLowerCase() !== ".png" && lastName.toLowerCase() !== ".jpeg") {
                this.$message.error("文件必须为.jpg,.png,.jpeg类型");
                isAccept = false;
                // 清空文件列表
                const newFileList = this.fileList.slice();
                newFileList.splice(0, 1);
                this.fileList = newFileList;
            }
        },
        async submitUpload() {
            const fileArray = this.fileList;
            console.log();
            this.fileArray = fileArray
            var formData = new FormData();
            for (let i = 0; i < fileArray.length; i++) {
                formData.append('file', fileArray[i].raw)
            }
            axios.post('/submit', formData, {
                "Content-type": "multipart/form-data"
            }).then(res => {
                console.log(res);
                if (res.data.code == 200) {
                    console.log(2222);
                    this.imgList = res.data.imgList;
                    this.onload({ page: this.currentPage, size: this.pageSize })
                    alert("上传成功")
                    this.fileList = []
                    this.dialogVisible = false
                }
            })
        },
        closemodal() {
            this.dialogaddFormVisible = false
            this.fileList = []
            this.addform = []
        },
        showDesc(index, row) {
            this.desci = index
            console.log(this.tableData[this.desci].comimgs);
            this.dialogdescFormVisible = true
        }
    },
    mounted() {
        //页面加载完成后，将数据库内的内容赋给定义的data变量
        this.init()
    }
}
</script>
<style scoped>
#sidepart {
    width: 100%;
    position: absolute;
    top: 5px;
    font-family: '华文中宋';
}

#mainpart {
    width: 100%;
    position: absolute;
    top: 20px;
    /* left: 260px; */
    font-family: '华文中宋';
}

#spanpart {
    font-size: 30px;
    font-family: '华文中宋';
}

/* dialog */
.el-button--text {
    margin-right: 15px;
}

.el-select {
    width: 300px;
}

.el-input {
    width: 300px;
}

.dialog-footer button:first-child {
    margin-right: 10px;
}

#spanlittlepart {
    font-size: 15px;
    color: cadetblue;
    font-family: '华文中宋';
}

.addbtn {
    width: 100%;
    margin: 0 auto;
    margin-bottom: 20px;
    font-family: '华文中宋';
    position: relative;
    left: 0px;
}
</style>